package com.kob.backend.service.impl.user.account;

import com.kob.backend.pojo.User;
import com.kob.backend.service.impl.utils.UserDetailsImpl;
import com.kob.backend.service.user.account.LoginService;
import com.kob.backend.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;//Spring Security 的 “认证管理器”，判断用户名密码是否有效
    @Override
    public Map<String, String> getToken(String username, String password) {
        //Spring Security 中,把用户名和密码加密
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        //验证用户名密码是否有效，能不能正常登录,登录失败会自动处理
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //从认证成功的 Authentication 对象中，获取用户详情,再取出用户信息
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticate.getPrincipal();
        User user = loginUser.getUser();
        //用用户id生成jwt令牌
        String jwt = JwtUtil.createJWT(user.getId().toString());
        //成功之后定义返回结果
        Map<String, String> map=new HashMap<>();
        map.put("error_message", "success");
        map.put("token", jwt);
        return map;
    }
}
